package org.example.forum.interceptor;

import org.example.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${forum.login.url}")
    private String defaultUrl;

    /**
     * 前置处理(对请求的预处理)
     * @return true 继续流程 false 中途流程
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            //用户已登录，通过校验
            return true;
        }
        //检验url是否正确
        if(!(defaultUrl.startsWith("/"))){
            defaultUrl = "/" + defaultUrl;
        }
        //校验不通过，跳转到登录界面
        response.sendRedirect(defaultUrl);
        return false;
    }


}
